import {Component} from '@angular/core';
import {
    AlertController, IonicPage, LoadingController, NavController, NavParams, Platform,
    ToastController
} from 'ionic-angular';
import {SystemService} from "../../service/SystemService";
import {Log} from "../../../framework/utils/Log";
import {Tag} from "@angular/compiler/src/i18n/serializers/xml_helper";
import {BasePage} from "../../BasePage";
//import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner/ngx';
import {BarcodeScanner} from "@ionic-native/barcode-scanner";

/**
 * Generated class for the PanDianDetailsPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
    selector: 'page-pan-dian-details',
    templateUrl: 'pan-dian-details.html',
})
export class PanDianDetailsPage extends BasePage {
    public panDianDBH: any;
    public static Tag: string = 'PanDianDetailsPage';
    public propertyDetailList:any=[];
    private tempPropertyDetailList:any=[];
    private saoCodeBool:boolean=false;
    private scannedCode: any;
    private searchKey:any={
        name:''
    };
    constructor(public platform: Platform,
                public navCtrl: NavController,
                public navParams: NavParams,
                public sys: SystemService,
                public loadingCtrl: LoadingController,
                public toastCtrl: ToastController,
                private barcodeScanner: BarcodeScanner,
                //public qrScanner: QRScanner,
                public alertCtrl: AlertController) {
        super(platform, loadingCtrl, toastCtrl, alertCtrl);
        this.panDianDBH  = this.navParams.data.code;
    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad PanDianDetailsPage');
        this.getPropertyDetailList();
    }

    getPropertyDetailList() {
        //this.showLoading(true,'');
        let data: any = {PanDianDBH: this.panDianDBH};
        this.sys.panDetialUrl(data).subscribe((res: any) => {
            if (res.msgCode == '1') {
                this.propertyDetailList = res.list;
                this.propertyDetailList.forEach(val=>{
                    if(val.ShiCunSL==""){
                        val.ShiCunSL=0;
                    }
                    /*if(val.ZiChanKP !=''){
                        val.ZiChanKP=this.nameStr(val.ZiChanKP);
                    }*/
                });
                this.tempPropertyDetailList = JSON.parse(JSON.stringify(this.propertyDetailList));
                Log.printObj(PanDianDetailsPage.Tag, "盘点资产详情信息=", res.list);
            }
        }, error => {

        })
    }
    scanCode(){
        this.saoCodeBool=true;
        /* this.qrScanner.prepare()
            .then((status: QRScannerStatus) => {
                if (status.authorized) {
                    // camera permission was granted
                    // start scanning
                    let scanSub = this.qrScanner.scan().subscribe((text: string) => {
                        console.log('Scanned something', text);
                        if(this.saoCodeBool){
                            setInterval(()=>{
                                this.propertyDetailList.forEach((val,index)=>{
                                    if(val.BianHao ==text){
                                        Number(val.ShiCunSL++);
                                        this.removeArr(index,this.propertyDetailList);
                                    }
                                })
                            },5000)
                        }
                        this.qrScanner.hide(); // hide camera preview
                        scanSub.unsubscribe(); // stop scanning
                    });

                } else if (status.denied) {
                    console.log('拒绝访问')
                    // camera permission was permanently denied
                    // you must use QRScanner.openSettings() method to guide the user to the settings page
                    // then they can grant the permission from there
                } else {
                    console.log('其他错误')
                    // permission was denied, but not permanently. You can ask for permission again at a later time.
                }
            })
            .catch((e: any) => console.log('Error is', e));*/
        this.barcodeScanner.scan().then(barcodeData => {
            this.scannedCode = barcodeData.text;
            for(let i=0;i<this.propertyDetailList.length;i++){

                if(this.propertyDetailList[i].ZiChanKP ==this.scannedCode){

                    Number(this.propertyDetailList[i].ShiCunSL++);
                    //alert(Number(this.propertyDetailList[i].ShiCunSL++))
                    this.removeArr(i,this.propertyDetailList);
                    break;
                }
            }
        }, (err) => {
            //console.log('Error: ', err);
        });

    }
    minus(item){
        let id:any=Number(item.ShiCunSL);
        if(Number(item.ShiCunSL)>0){
            Number(item.ShiCunSL--);
        }
    }
    save(name){
        let dataList:any=[];
        this.propertyDetailList.forEach(val=>{
            dataList.push({PanDianMXBH:val.BianHao,ShuLiang:String(val.ShiCunSL)});
        });
        let data:any={
            PanDianDBH:this.panDianDBH,
            PanDianCZ:name,
            panList:dataList
        };

       this.sys.panDianConfirm(data).subscribe((res:any)=>{
           if (res.msgCode == '1') {
               Log.printObj(PanDianDetailsPage.Tag, "盘点完成信息=", res);
               this.showToast("盘点成功");
               this.navCtrl.pop();
              
           }else {
               this.showToast(res.msg)
           }
       }),error=>{
           this.showError("盘点失败")
        }
    }
    sure(name){
        this.save(name);
    }
    removeArr(id, arr) {
        let item:any=arr[id];
        arr.splice(id, 1);
        arr.unshift(item);
    }
    search(name){
        let reg = new RegExp(this.searchKey.name);
        let arr:any = [];
        if(this.searchKey.name !=""){
            this.propertyDetailList.forEach((value,index)=>{
                if(value.ZiChanMC.match(reg)){
                    arr.push(this.propertyDetailList[index]);
                }
            });
            this.propertyDetailList=arr;
        }else {
            this.propertyDetailList = this.tempPropertyDetailList;
        }
    }
    nameStr(str: string) {
        let strend: any;
        strend = str.substring(str.length - 4);
        let strStart: any = str.substring(0, 1);
        let name: string = strStart + '..' + strend;

        return name;

    }
}
